#include "editorgalleryitem.h"

#include "gallerycommon.h"

#include <QtCore/QMimeData>
#include <QtCore/QSize>
#include <QtCore/QUrl>
#include <QtGui/QAction>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QDrag>
#include <QtGui/QIcon>
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>

using namespace gui;

EditorGalleryItem::EditorGalleryItem(const QPixmap& galleryThumbnail,
    const QString& label, QAction* action, const QPixmap& dragThumbnail,
    QMimeData* dragData, QWidget* parent) : QToolButton(parent),
        m_dragStartPosition(),
        m_dragData(dragData),
        m_dragThumbnail(dragThumbnail)
{
    setText(label);
    setIcon(QIcon(galleryThumbnail));
    setIconSize(QSize(PREFERRED_GAL_ITEM_ICON_SIZE,
        PREFERRED_GAL_ITEM_ICON_SIZE));
    setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    setCheckable(false);

    if (action != 0)
    {
        connect(this, SIGNAL(clicked()), action, SIGNAL(triggered()));
    }
}

EditorGalleryItem::~EditorGalleryItem()
{

}

void EditorGalleryItem::mousePressEvent(QMouseEvent* event)
{
    if (m_dragData != 0 && event->button() == Qt::LeftButton)
    {
        m_dragStartPosition = event->pos();
    }

    QToolButton::mousePressEvent(event);
}

void EditorGalleryItem::mouseMoveEvent(QMouseEvent* event)
{
    if (m_dragData != 0 && ((event->buttons() & Qt::LeftButton) == Qt::LeftButton))
    {
        if ((event->pos() - m_dragStartPosition).manhattanLength()
              >= QApplication::startDragDistance())
        {
            QDrag* drag = new QDrag(this);

            if (m_dragData != 0)
            {
                QMimeData* mimeData = new QMimeData;

                foreach (const QString& format, m_dragData->formats())
                {
                    mimeData->setData(format, m_dragData->data(format));
                }

                drag->setMimeData(mimeData);
            }

            drag->setPixmap(m_dragThumbnail);
            drag->setHotSpot(QPoint(m_dragThumbnail.width()/2,
                m_dragThumbnail.height()/2));

            drag->exec();

            setDown(false);
        }
    }
}
